import bean.LocationResult;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

public class FilesHandler {

    //存放文件名称的list
    private static List<String> mList;
    //存放每条合理数据的list
    private static List<LocationResult> resultList;
    //存放设备名称的list
    private static List<String> devicesList;
    //使用HashSet自动去重，直接获得实际的设备mac
    private static HashSet<String> devicesSet;
    private static Map<String, Double> resultMap;

    private static String path = System.getProperty("user.dir")+"\\src" +  "\\result\\";

    //需要用到的AP的mac值
    private static String[] mac_list = {"C2:01:AB:00:03:E2","C2:01:B0:00:03:E8","C2:01:AB:00:03:DD","C2:01:B0:00:03:E4","C2:01:AB:00:03:DF",
            "C2:01:AB:00:03:DC","C2:01:AB:00:03:DE","C2:01:B0:00:03:E5","C2:01:B0:00:03:E6","C2:01:B0:00:03:E3"};

    //最终的按照上述mac值进行排序的rssi平均强度，初始化为-500
    public static double[] finalRes = {-500, -500, -500, -500, -500, -500, -500, -500, -500, -500};

    private static int task = -1;

    public static void main(String[] args) throws IOException {
        mList = new ArrayList<>();
        System.out.println("请输入要扫描的文件夹路径：");
        Scanner scanner = new Scanner(System.in);
        String targetPath = scanner.nextLine();
        boolean flag = getFiles(targetPath);
        createFile();
        if (flag) {
            for (int i = 0; i < mList.size(); i++) {
                //将三个list放在循环中初始化，每读一个新的文件都会重新初始化上一次的list
                String getContent = readFile(targetPath + "\\" +  mList.get(i));
                resultMap = new HashMap<>();
                resultList = new ArrayList<>();
                devicesSet = new HashSet<>();
                devicesList = new ArrayList<>();
                txtHandler(getContent);
                devicesList.addAll(devicesSet);
                System.out.println(mList.get(i) + "结果如下：");
                writeContent(mList.get(i) + "文件的处理的结果是:");
                for (int j = 0; j < devicesList.size(); j++) {
                    int sum = 0, time = 0;
                    double ans, variance, varianceSum = 0;
                    for (int k = 0; k < resultList.size(); k++) {
                        if (devicesList.get(j).equals(resultList.get(k).getMac())) {
                            sum = sum + resultList.get(k).getRssi();
                            time++;
                        }
                    }
                    //求得平均值
                    ans = (double)sum / (double) time;
                    for (int k = 0; k < resultList.size(); k++) {
                        varianceSum = varianceSum + Math.pow((ans - resultList.get(k).getRssi()), 2);
                    }
                    variance = varianceSum / time;
                    String result = "mac: " + devicesList.get(j) + ", avg: " + ans;
                    writeContent(result);
                    System.out.println("设备 " + devicesList.get(j) + "的平均RSSI值为：" + ans + ",出现了" + time+
                            "次" + "和为" + sum + ", 方差为：" + variance);
                    resultMap.put(devicesList.get(j), ans);
                    for (int k = 0; k < resultMap.size(); k++) {
                        Iterator<String> iterator = resultMap.keySet().iterator();
                        while (iterator.hasNext()) {
                            String mac = iterator.next();
                            if (isInList(mac)) {
                                finalRes[task] = resultMap.get(mac);
                            }
                        }
                    }
                }
                System.out.println(Arrays.toString(finalRes));
                KnnTest.execute(finalRes);
            }
        }
    }

    //判断设备是否为特定的AP设备
    private static boolean isInList(String mac) {
        for (int i = 0; i < mac_list.length; i++) {
            if (mac.equals(mac_list[i])) {
                //根据实际找到的位置赋值
                task = i;
                return true;
            }
        }
        return false;
    }

    /**
     * 对文本中的内容进行处理
     * @param content 文本内容
     */
    private static void txtHandler(String content) {
        String strContent[] = content.split("\n");
        for (int i = 0; i < strContent.length; i++) {
            String details[] = strContent[i].split(",");
            //System.out.println(Arrays.toString(details));
            String name = details[0];
            String mac = details[1].substring(4, details[1].length());
            int rssi = Integer.parseInt(details[2].substring(5, details[2].length()));
            if (!name.equals("null") && rssi >= -100) {
                resultList.add(new LocationResult(name, rssi, mac));
                devicesSet.add(mac);
            }
        }
    }

    /**
     * 获取当前目录下所有以txt后缀的文件
     * @param dirPath 文件夹路径
     * @return boolean值，判断文件夹下是否存在txt文件
     */
    private static boolean getFiles(String dirPath) {
        File file = new File(dirPath);
        File[] fileArray = file.listFiles();
        for (File aFileArray : fileArray) {
            if (aFileArray.toString().endsWith(".txt") && aFileArray.isFile()) {
                mList.add(aFileArray.getName());
            }
        }
        return mList.size() > 0;
    }

    /**
     * 读取文件内容的方法
     * @param filePath txt文件的路径
     * @return 将文件中所有内容以String方式取得
     */
    static String readFile(String filePath){
        StringBuilder builder = new StringBuilder();
        try {
            String encoding="UTF-8";
            File file=new File(filePath);
            if(file.isFile() && file.exists()){ //判断文件是否存在
                InputStreamReader read = new InputStreamReader(new FileInputStream(file),encoding);//考虑到编码格式
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt;
                while((lineTxt = bufferedReader.readLine()) != null){
                    lineTxt = lineTxt + "\n";
                    builder.append(lineTxt);
                }
                read.close();
            }else{
                System.out.println("找不到指定的文件");
            }
        } catch (Exception e) {
            System.out.println("读取文件内容出错");
            e.printStackTrace();
        }
        return builder.toString();
    }

    /**
     * 创建一个txt文件并向其中写入得到的平均值结果
     * @return 是否成功创建了文件
     * @throws IOException
     */
    private static boolean createFile() throws IOException {
        boolean flag = false;
        path = path + getTime() + ".txt";
        File filename = new File(path);
        if (!filename.exists()) {
            filename.createNewFile();
            flag = true;
        }
        return flag;
    }

    private static void writeContent(String content) {
        FileWriter writer = null;
        try {
            writer = new FileWriter(path, true);
            writer.write(content + "\r\n");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(writer != null){
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    static String getTime() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");// HH:mm:ss
        Date date = new Date(System.currentTimeMillis());
        return simpleDateFormat.format(date);
    }
}
